package com.shujia.flink.state

import org.apache.flink.api.common.eventtime.WatermarkStrategy
import org.apache.flink.api.common.serialization.SimpleStringSchema
import org.apache.flink.connector.kafka.source.KafkaSource
import org.apache.flink.connector.kafka.source.enumerator.initializer.OffsetsInitializer
import org.apache.flink.runtime.state.hashmap.HashMapStateBackend
import org.apache.flink.streaming.api.CheckpointingMode
import org.apache.flink.streaming.api.environment.CheckpointConfig.ExternalizedCheckpointCleanup
import org.apache.flink.streaming.api.functions.KeyedProcessFunction
import org.apache.flink.streaming.api.scala._
import org.apache.flink.util.Collector

import scala.collection.mutable

object Demo1NoState {
  def main(args: Array[String]): Unit = {
    val env: StreamExecutionEnvironment = StreamExecutionEnvironment.getExecutionEnvironment

    /**
     * 开启checkpoint
     *
     */

    // 每 5000ms 开始一次 checkpoint
    env.enableCheckpointing(5000)

    // 高级选项：

    // 设置模式为精确一次 (这是默认值)
    env.getCheckpointConfig.setCheckpointingMode(CheckpointingMode.EXACTLY_ONCE)

    // 确认 checkpoints 之间的时间会进行 500 ms
    env.getCheckpointConfig.setMinPauseBetweenCheckpoints(500)

    // Checkpoint 必须在一分钟内完成，否则就会被抛弃
    env.getCheckpointConfig.setCheckpointTimeout(60000)

    // 允许两个连续的 checkpoint 错误
    env.getCheckpointConfig.setTolerableCheckpointFailureNumber(2)

    // 同一时间只允许一个 checkpoint 进行
    env.getCheckpointConfig.setMaxConcurrentCheckpoints(1)

    // 使用 externalized checkpoints，这样 checkpoint 在作业取消后仍就会被保留
    env.getCheckpointConfig.setExternalizedCheckpointCleanup(
      ExternalizedCheckpointCleanup.RETAIN_ON_CANCELLATION)


    //设置状态后端，保存状态的位置
    //HashMapStateBackend:将状态保存在内存中
    env.setStateBackend(new HashMapStateBackend())

    //状态持久化位置
    env.getCheckpointConfig.setCheckpointStorage("hdfs://master:9000/flink/checkpoint")




    val source: KafkaSource[String] = KafkaSource
      .builder[String]
      //kafka 集群列表
      .setBootstrapServers("master:9092,node1:9092,node2:9092")
      //消费的topic
      .setTopics("lines")
      //消费者组
      .setGroupId("my-group")
      //读取数据的位置，earliest：从最早读取数据，latest：读取最新数据
      .setStartingOffsets(OffsetsInitializer.earliest)
      .setValueOnlyDeserializer(new SimpleStringSchema())
      .build

    //使用kafka 数据源
    val linesDS: DataStream[String] = env
      .fromSource(source, WatermarkStrategy.noWatermarks(), "Kafka Source")


    val wordsDS: DataStream[String] = linesDS.flatMap(_.split(","))

    val keyByDS: KeyedStream[String, String] = wordsDS.keyBy(word => word)

    val countDS: DataStream[(String, Int)] = keyByDS
      .process(new KeyedProcessFunction[String, String, (String, Int)] {

        //count变量在每一个task有一个，task中所有的单词共用同一个，会导致结果出错
        //var count = 0

        /**
         * 将计算结果保存再map集合中会丢失数据
         * 1、任务重启，map集合中的数据就没了
         */
        private val map = new mutable.HashMap[String, Int]()

        /**
         * processElement: 每一条数据执行一次
         *
         * @param word ：单词
         * @param ctx  ：上下文对象
         * @param out  ：用于将数据发送到下游
         */
        override def processElement(word: String,
                                    ctx: KeyedProcessFunction[String, String, (String, Int)]#Context,
                                    out: Collector[(String, Int)]): Unit = {
          //计算单词的数量
          //count += 1

          var count: Int = map.getOrElse(word, 0)

          //累加计算
          count += 1

          map.put(word, count)

          //发送数据到下游
          out.collect((word, count))
        }
      })

    countDS.print()

    env.execute()

  }

}
